//
//  ViewController.m
//  HeSaid
//
//  Created by MWJ on 15/5/4.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import <MapKit/MKAnnotation.h>
#import "ViewController.h"
#import "AnnotationView.h"
#import "AppDelegate.h"
#import "Bubble.h"
#import "registeredViewController.h"  //注册界面
#import "PersonViewController.h" //个人中心界面
#import "PostViewController.h"  //发帖子界面
#import "SetUpViewController.h" //设置界面
#import "HotPostViewController.h"    //热门帖界面
#import "PostDetailViewController.h" //帖子详情界面
#import "Reachability.h"
#define roundIDURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/seek_homeId"
#define roundURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/seek_homeMessage"
#define perURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/PersonalCenter"

@interface ViewController (){
    CLLocationManager *locationManager;
    CLGeocoder *geocoder;
    CLPlacemark *Placemark;
    AppDelegate *app;
    NSMutableArray *perArray;
    NSMutableArray *roundIdarr;
    NSMutableArray *roundArray;
    NSDictionary *roundArray1;
    NSMutableArray *smallArray;
    int judge;
    NSString *roundId;
    NSMutableArray *tourArray;
    NSMutableArray *idArray;
    int idindex;
    AnnotationView *oneView;
    UIScrollView *_sView;
    UIScrollView *sView;
    int intid;
}

@end

@implementation ViewController
-(void)viewWillAppear:(BOOL)animated{
    [app isConnectionAvailable];
    if ([app.Existence isEqualToString:@"1"]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前网络不可用，请检查网络连接！"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
<<<<<<< HEAD
=======
    }else{
    app.defaults = [NSUserDefaults standardUserDefaults];
    app.user_id = [app.defaults objectForKey:@"yonghu"];
    idindex = 0;
    if ([app.user_id isEqualToString:@""]||app.user_id==nil) {
>>>>>>> 4b04801d95a25eb22fcb8820da68a35773c3052f
    }else{
        app.defaults = [NSUserDefaults standardUserDefaults];
        app.user_id = [app.defaults objectForKey:@"yonghu"];
        idindex = 0;
        if ([app.user_id isEqualToString:@""]||app.user_id==nil) {
        }else{
            [self per];
        }
        //周围信息
        [self round];
        //开始定位
        [locationManager startUpdatingLocation];
    }
        //周围信息
        [self round];
        //开始定位
        [locationManager startUpdatingLocation];
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
    idindex = 0;
}
-(BOOL)canBecomeFirstResponder {
    return YES;
}
-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
} 
#pragma mark - 页面加载
- (void)viewDidLoad {
    [super viewDidLoad];
    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    [[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];
    [self becomeFirstResponder];
    self.navigationItem.hidesBackButton = YES;
    self.CurrentLocation.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerIncident)];
    [self.CurrentLocation addGestureRecognizer:singleFingerOne];
    tourArray = [NSMutableArray array];
    perArray = [NSMutableArray array];
    roundIdarr = [NSMutableArray array];
    roundArray = [NSMutableArray array];
    smallArray = [NSMutableArray array];
    idArray=[NSMutableArray array];
    
    //下拉菜单
    [self menu];
    self.navigationItem.title=@"首页";
    //创建右边菜单按钮
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"02.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightmenu)];
    self.navigationItem.rightBarButtonItem = item;
    
    //创建左边菜单
    UIBarButtonItem *leftitem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"01.png"] style:UIBarButtonItemStylePlain target:self action:@selector(personmenu)];
    self.navigationItem.leftBarButtonItem = leftitem;
    
    self.navigationController.navigationBar.translucent = NO;
    //创建定位管理器
    locationManager = [[CLLocationManager alloc] init];
    geocoder=[[CLGeocoder alloc]init];
    //设置返回全部信息
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    //设置定位精度
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
    {
        //设置定位权限 仅ios8有意义
        [locationManager requestWhenInUseAuthorization];// 前台定位
        
        //  [locationManager requestAlwaysAuthorization];// 前后台同时定位
    }
<<<<<<< HEAD
=======
    
>>>>>>> 4b04801d95a25eb22fcb8820da68a35773c3052f
    //计时器，10分钟做一次地图刷新
    NSTimer *timer=[[NSTimer alloc]init];
    timer=[NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timetoRefresh) userInfo:nil repeats:YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==10000) {
        if (buttonIndex==1) {
            NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com"];
            [[UIApplication sharedApplication]openURL:url];
        }
    }
}
-(void)fingerIncident{
    //开始定位
    [self timetoRefresh];
    [locationManager startUpdatingLocation];
}
#pragma mark - 请求用户信息，拿到用户的头像，积分数
-(void)per{
    NSURL *url=[NSURL URLWithString:perURL];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *poststr =[NSString stringWithFormat:@"user_id=%@",app.user_id];
    NSData *data=[poststr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        perArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:perArray waitUntilDone:YES];
        for (NSDictionary *dic in perArray) {
            app.Portrait = dic[@"user_HeadPortrait"];
            app.integralCount=dic[@"user_count"];
        }
         }];
}
#pragma mark - 定时刷新，10分钟刷一次
-(void)timetoRefresh{
    [self.mapview removeAnnotations:self.locationsMutArray];
    [self.locationsMutArray removeAllObjects];
    [idArray removeAllObjects];
    [self all];
    
}

#pragma mark - 左边按钮
-(void)personmenu{
    if (app.user_id == nil||[app.user_id isEqualToString:@""]) {
        registeredViewController *reg = [self.storyboard instantiateViewControllerWithIdentifier:@"registeredVC"];
        [self.navigationController pushViewController:reg animated:YES];
    }else{
        PersonViewController *per = [self.storyboard instantiateViewControllerWithIdentifier:@"personViewController"];
        [self.navigationController pushViewController:per animated:YES];
    }
}

#pragma mark - 下拉控件
-(void)menu{
    
    //第一个按钮
    UIView *postItem = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];
    [postItem setMenuActionWithBlock:^{
        //点击事件
        if (app.user_id == nil||[app.user_id isEqualToString:@""]) {
            registeredViewController *reg = [self.storyboard instantiateViewControllerWithIdentifier:@"registeredVC"];
            [self.navigationController pushViewController:reg animated:YES];
        }else{
            PostViewController *post=[self.storyboard instantiateViewControllerWithIdentifier:@"postVC"];
            [self.navigationController pushViewController:post animated:YES];
        }
        
    }];
    UIImageView *postIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [postIcon setImage:[UIImage imageNamed:@"post"]];
    UILabel *post = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 30, 15)];
    post.text = @"发帖";
    post.textAlignment=NSTextAlignmentCenter;
    post.font = [UIFont boldSystemFontOfSize:15.0f];
    [postItem addSubview:postIcon];
    [postItem addSubview:post];
    
    //第二个按钮
    UIView *hotpostItem = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];
    [hotpostItem setMenuActionWithBlock:^{
        //点击事件
        HotPostViewController *hotPost=[self.storyboard instantiateViewControllerWithIdentifier:@"hotPostVC"];
        [self.navigationController pushViewController:hotPost animated:YES];
        
    }];
    UIImageView *hotpostIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [hotpostIcon setImage:[UIImage imageNamed:@"hotPost"]];
    UILabel *hotpost = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 30, 15)];
    hotpost.text = @"热帖";
    hotpost.textAlignment=NSTextAlignmentCenter;
    hotpost.font = [UIFont boldSystemFontOfSize:15.0f];
    [hotpostItem addSubview:hotpostIcon];
    [hotpostItem addSubview:hotpost];
    self.sideMenu = [[HMSideMenu alloc] initWithItems:@[postItem, hotpostItem]];
    //按钮上下的间距
    [self.sideMenu setItemSpacing:10.0f];
    [self.view addSubview:self.sideMenu];
}
#pragma mark - 右边按钮菜单点击事件
-(void)rightmenu{
    if (self.sideMenu.isOpen)
        [self.sideMenu close];
    else
        [self.sideMenu open];
}
#pragma mark - 显示所有用户
-(void)round{
    judge = 1;
    NSURL *url=[NSURL URLWithString:roundIDURL];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *poststr =[NSString stringWithFormat:@"message=%d",judge];
    NSData *data=[poststr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        roundArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:roundArray waitUntilDone:YES];
        for (NSDictionary *dic in roundArray) {
            Bubble *bubble = [[Bubble alloc]init];
            bubble.message_id = dic[@"message_id"];
            [tourArray addObject:bubble];
        }
        [self all];
    }];
}

#pragma mark - 自定义大头针

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    
    if ([annotation isKindOfClass:[AnnotationView class]]) {
        static NSString* kPin = @"DTZ";
        AnnotationView *pinView = (AnnotationView *)
        [mapView dequeueReusableAnnotationViewWithIdentifier:kPin];
        if (!pinView) {
            pinView = [[AnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:kPin];
            pinView.canShowCallout=YES;//允许交互点击
            pinView.calloutOffset=CGPointMake(0, 5);//定义详情视图偏移量
            pinView.selected=YES;
            
            UIButton *rightButton=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            [rightButton setBackgroundImage:[UIImage imageNamed:@"02.png"] forState:UIControlStateNormal];            if ([app.user_sex isEqualToString:@"女"]) {
                
                pinView.rightCalloutAccessoryView=rightButton;  //设置气泡右侧按钮
                
            }else{
                
                pinView.leftCalloutAccessoryView = rightButton;   //设置气泡左边按钮
                
                
            }
            rightButton.tag = 1000 + idindex++;

            [rightButton addTarget:self action:@selector(ButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        }
        return pinView;
    }
    return nil;
}

#pragma mark - 文字气泡上的按钮的点击事件

-(void)ButtonClick:(UIButton *)button{
    app.message_id = idArray[intid];
    PostDetailViewController *postDetailVC=[self.storyboard instantiateViewControllerWithIdentifier:@"postDetailVC"];
    [self.navigationController pushViewController:postDetailVC animated:YES];
}

-(void)refreshData{
    
}
-(void)all{
    self.locationsMutArray=[NSMutableArray array];
    for (NSDictionary *dic in roundArray) {
        AnnotationView *tourLocation=[[AnnotationView alloc]init];
        tourLocation.title=[dic[@"message_content"] substringToIndex:12];
        tourLocation.latitude=dic[@"message_latitude"];
        tourLocation.longitude=dic[@"message_longitude"];
        tourLocation.messageId = dic[@"message_id"];
        tourLocation.showTime = dic[@"message_showtime"];
        app.showTime=tourLocation.showTime;
        tourLocation.releaseTime= dic[@"message_time"];
        //把经度纬度封装
        tourLocation.coordinate=CLLocationCoordinate2DMake([dic[@"message_latitude"] doubleValue],[dic[@"message_longitude"]doubleValue]);
        //当下时间 － 显示时间 和 发表时间比较大小，如果大于，不显示，如果小于，显示
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        //当下时间
        NSDate *date=[NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval now=[date timeIntervalSince1970]*1;
        //发表时间
        NSDate *date2=[dateFormatter dateFromString:tourLocation.releaseTime];
        NSTimeInterval before=[date2 timeIntervalSince1970]*1;
        //两个日期之间相隔多少秒
        NSTimeInterval cha= now - before;
        //大于  等于
        
        if (cha/3600 < 1) {
            if ((cha/60 > [tourLocation.showTime intValue]) ||(cha/60 == [tourLocation.showTime intValue])) {
                
                //显示时间结束后，执行事件
                NSTimer *timer=[[NSTimer alloc]init];
                timer=[NSTimer scheduledTimerWithTimeInterval:cha target:self selector:@selector(timeEnd) userInfo:nil repeats:NO];
            }
            //小于
            else{
                [self.locationsMutArray addObject:tourLocation];
                
                //帖子的ID放到一个数组里
                [idArray addObject:tourLocation.messageId];
                [idArray addObject:tourLocation.title];
            }
        }
        
        [self.mapview addAnnotations:self.locationsMutArray];
        
    }
}

#pragma mark - 显示时间结束后，执行事件
-(void)timeEnd{
    AnnotationView *tourLocation=self.locationsMutArray[idindex];
        [self.locationsMutArray removeObject:tourLocation];
}
#pragma mark - 定位
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if (error.code==kCLErrorLocationUnknown) {
        NSLog(@"无法获取到当前位置信息");
    }else if (error.code==kCLErrorNetwork){
        NSLog(@"网络异常");
    }else if (error.code==kCLErrorDenied){
        NSLog(@"您的phone禁用获取位置服务");
    }
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取位置信息失败"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    CLLocation *currentLocation=newLocation;
    NSString *locstr1 = @"http://restapi.amap.com/v3/assistant/coordinate/convert?locations=";
    NSString *locstr2 = [NSString stringWithFormat:@"%f,%f",currentLocation.coordinate.longitude,currentLocation.coordinate.latitude];
    NSString *locstr3 = @"&coordsys=gps&output=json&key=b1ba3d04de3c8efdc866712f66033064";
    NSString *locstr4 = [NSString stringWithFormat:@"%@%@%@",locstr1,locstr2,locstr3];
    NSURL *url=[NSURL URLWithString:locstr4];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    NSString *poststr =@"";
    NSData *data=[poststr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        roundArray1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:roundArray1 waitUntilDone:YES];
        NSArray *strarray = [roundArray1[@"locations"] componentsSeparatedByString:@","];
        _longitude = [strarray[0] doubleValue];
        _latitude = [strarray[1] doubleValue];
        
        if (currentLocation!=nil) {
            //停止获取地址位置
            [locationManager stopUpdatingLocation];
            //转换地址
            [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
                if (error==nil&&[placemarks count]>0) {
                    Placemark=[placemarks lastObject];
                    NSString *s1=[[NSString alloc]init];
                    //地标的名字
                    s1=[NSString stringWithFormat:@"%@",Placemark.name];
                }else{
                    UIAlertView *Alert = [[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [Alert show];
                    
                }
            }];
        }
        //    [self.mapview setShowsUserLocation:YES];
        
        [self setShowMapLongitude:_longitude latitude:_latitude];
//        }
    }];

}

#pragma mark - 显示当前位置

-(void)setShowMapLongitude:(double)longitude latitude:(double)latitude{
//    //设置经纬度
    CLLocationCoordinate2D coord={latitude,longitude};
//    //设置显示范围精度
    MKCoordinateSpan span={0.005,0.005};
//    //显示范围
    MKCoordinateRegion region={coord,span};
//    //给地图设置显示区域
    [self.mapview setRegion:region animated:YES];

}

#pragma mark - 随机显示一个标注
-(void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views{
    
    
    for (int i=0; i<self.mapview.annotations.count; i++) {

        [self.mapview selectAnnotation:[self.mapview.annotations objectAtIndex:i] animated:YES];
        
        oneView=[self.mapview.annotations objectAtIndex:i];
        for (int i = 0; i < idArray.count; i++)
        {
            if (idArray[i] == oneView.title)
            {
                intid = i-1;
            }
        }
        }

    [self setShowMapLongitude:[oneView.longitude floatValue] latitude:[oneView.latitude floatValue]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 检测到摇动
//- (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event



#pragma mark - 摇动取消
//- (void) motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event



#pragma mark - 摇动结束
- (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

{
    
    //摇动结束
        if (event.subtype == UIEventSubtypeMotionShake) {
            
//            [self RandomDisplay];
            [self timetoRefresh];
//            [self mapView:nil didAddAnnotationViews:nil];
        }
    
}

#pragma mark - 随机显示
//-(void)RandomDisplay{
//
//
//        for (int i=0; i<self.mapview.annotations.count; i++) {
//            
//            [self.mapview selectAnnotation:[self.mapview.annotations objectAtIndex:(arc4random() % (i+1))] animated:YES];
//            
//            oneView=[self.mapview.annotations objectAtIndex:i];
//            
//            
//        }
//        
//        [self setShowMapLongitude:[oneView.longitude floatValue] latitude:[oneView.latitude floatValue]];
//
//}

@end
